import requests
import json
from read_search_file import  return_headers
from loguru import logger

url = "https://ad.xiaohongshu.com/api/leona/asset/directLink/create" # 直达链接添加接口

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
def collect_direct_link_list_exists(cookies=None, account_id=None, data=None, log_callback=None):
    headers = return_headers(account_id=account_id)

    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)

    res_json = response.json()

    if res_json.get('code') == 0:
        data_res = res_json.get('data')
        log_message(log_callback, f'直达链接新增成功,此次共新增{len(data_res)}条链接', "green")
        logger.info(f'直达链接新增成功,此次共新增{len(data_res)}条链接')
    else:
        error_code = res_json.get('code')
        error_msg = res_json.get('msg', '无提示信息')
        error_data = res_json.get('data', {})

        error_details = f"错误码: {error_code}, 提示信息: {error_msg}, 返回数据: {error_data}"
        log_message(log_callback, f'❌ 直达链接新增失败: {error_details}', "red")
        logger.error(f'直达链接新增失败 - 错误码: {error_code}, 提示信息: {error_msg}, 返回数据: {error_data}')